import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
    setLocalStorage,
    getLocalStorage,
    removeLocalStorage,
    setSessionStorage,
    getSessionStorage,
    removeSessionStorage
} from '@/common.js'

export const useAuthStore = defineStore('auth', () => {
    // 从存储中初始化状态
    const token = ref(getSessionStorage('token') || '')

    const isAuthenticated = computed(() => !!token.value)

    // 登录方法
    const login = async (loginResponse) => {
        try {
            if (loginResponse.data && loginResponse.data.id_token) {
                // 保存token
                token.value = loginResponse.data.id_token
                // console.log("token:"+token.value)

                // 使用工具函数存储数据
                setSessionStorage('token', token.value)

                return { success: true, data: loginResponse.data }
            } else {
                return { success: false, message: loginResponse.message || '登录失败' }
            }
        } catch (error) {
            console.error('登录存储错误:', error)
            return {
                success: false,
                message: error.message || '登录信息保存失败'
            }
        }
    }

    // 登出方法
    const logout = () => {
        token.value = ''

        // 使用工具函数清理数据
        removeSessionStorage('token')
        removeSessionStorage('userId')
        removeSessionStorage('userAuthorities')
        removeSessionStorage('business')
        removeSessionStorage('userInfo')
        removeSessionStorage('userRole')
    }

    // 获取token
    const getToken = () => {
        return token.value || getSessionStorage('token')
    }

    // 检查登录状态
    const checkAuth = () => {
        const storedToken =getSessionStorage('token')
        // console.log("checkAuth:",storedToken)
        if (storedToken) {
            token.value = storedToken
            return true
        }
        logout()
        return false
    }

    return {
        token,
        isAuthenticated,
        login,
        logout,
        getToken,
        checkAuth
    }
})